# _*_ coding : utf-8 _*_
# @Time : 2021/12/19 12:43
# @Author : hx
# @File : wangyiyun
# @Project : wangyiyundownload
import requests
import os
import shutil

share_link = os.getenv("JIANMU_SHARE_LINK")
share_dir = os.getenv("JM_SHARE_DIR")

music_name = share_link.split("《")[1].split("》")[0]
song_id = ""
if share_link.__contains__("https://y.music.163.com/m/song/"):
    song_id = share_link.split("https://y.music.163.com/m/song/")[1].split("/")[0]
else:
    song_id = share_link.split("https://y.music.163.com/m/song?id=")[1].split("&")[0]
print("song_id = " + song_id)
print("music_name = " + music_name)

url = 'http://music.163.com/song/media/outer/url?id=' + song_id + '.mp3'

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36'
}

response = requests.get(url=url, headers=headers)

with open(music_name + ".mp3", "wb") as code:
    code.write(response.content)

shutil.move("./" + music_name + ".mp3", share_dir)

# 处理返回结果
resultJson = "{\n\t\"download_music_path\" : \"" + share_dir + "/" + music_name + ".mp3" + "\"\n}"
resultFile = open('/tmp/downloadResultFile', 'w', encoding='utf-8')
resultFile.write(resultJson)
resultFile.close()
print(resultJson)
